package com.anyisn.anyflickr.shell.view
{
	import flash.events.Event;
	
	import mx.events.CloseEvent;
	import mx.managers.PopUpManager;
	
	import org.puremvc.as3.multicore.interfaces.INotification;
	
	import com.anyisn.anyflickr.shell.ShellFacade;
	import com.anyisn.anyflickr.shell.model.PeopleProxy;
	import com.anyisn.anyflickr.shell.view.components.itemrender.TagsTreeIR;
	import com.anyisn.anyflickr.shell.view.components.popup.PersonTW;
	import com.anyisn.puremvc.as3.multicore.patterns.mediator.AbstractPopupMediator;
	
	public class PersonTWMediator extends AbstractPopupMediator
	{
		public static const NAME:String = 'PersonTWMediator';
		
		public function PersonTWMediator(viewComponent:Object)
		{
			super(NAME, viewComponent);
			personTW.addEventListener(CloseEvent.CLOSE, close);
			personTW.addEventListener(PersonTW.ADD_TAG, addTag);
			personTW.addEventListener(TagsTreeIR.CHANGE, onTagChange);
			personTW.addEventListener(TagsTreeIR.DELETE, onTagDelete);
		}
		
		private function onTagDelete(e:Event):void {
			sendNotification(ShellFacade.TAG_DELETE, e.target.data.id);
		}
		
		private function onTagChange(e:Event):void {
			if(e.target.tag.selected) {
				sendNotification(ShellFacade.TAG_PUSH, e.target.data.id);
			} else {
				sendNotification(ShellFacade.TAG_REMOVE, e.target.data.id);
			}
		}
		
		private function addTag(e:Event):void {
			sendNotification(ShellFacade.TAG_ADD, personTW.tag.text);
		}
		
		public function close(e:CloseEvent = null):void {
			personTW.removeEventListener(CloseEvent.CLOSE, close);
			personTW.removeEventListener(PersonTW.ADD_TAG, addTag);
			personTW.removeEventListener(TagsTreeIR.CHANGE, onTagChange);
			personTW.removeEventListener(TagsTreeIR.DELETE, onTagDelete);
			
			PopUpManager.removePopUp(personTW);
			setViewComponent(null);
			facade.removeMediator(this.getMediatorName());
		}
		
		override public function listNotificationInterests() : Array {
			return [
					ShellFacade.TAGS_GET_LIST_FOR_PERSON_TW_SUCCESS
					];
		}
		
		override public function handleNotification(notification:INotification) : void {
			switch(notification.getName()) {
				case ShellFacade.TAGS_GET_LIST_FOR_PERSON_TW_SUCCESS:
					var tags:Array = notification.getBody() as Array;
					personTW.tagsList.dataProvider = tags;
					break;
			}
		}
		
		override public function onRegister() : void {
			var peopleProxy:PeopleProxy = facade.retrieveProxy(PeopleProxy.NAME) as PeopleProxy;
			personTW.data = peopleProxy.person;
			sendNotification(ShellFacade.TAGS_GET_LIST, this.getMediatorName());
		}
		
		private function get personTW():PersonTW {
			return viewComponent as PersonTW;
		}
	}
}